package com.xvyy.tingshu.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xvyy.tingshu.constant.CacheAbleConstant;
import com.xvyy.tingshu.exception.BloomCacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * ClassName: JSONDataFormatting
 * Package: com.xvyy.tingshu.utils
 *
 * @Description: 序列化与反序列化工具类：
 * 使用springboot原生的序列化与反序列化工具类jackson包下的ObjectMapper类
 * @Author: xvyy
 * @Create: 2025/2/9 - 14:16
 * @Version: v1.0
 */
public class JSONDataFormatting {

    static Logger logger = LoggerFactory.getLogger(JSONDataFormatting.class);
    static final ObjectMapper objectMapper = new ObjectMapper();
    static String cacheStr = null;

    /**
     * 反序列化：字符串转对象，不带泛型信息
     *
     * @param jsonContent
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T jsonToObject(String jsonContent, Class<T> clazz) {
        T t = null;
        try {
            t = objectMapper.readValue(jsonContent, clazz);
        } catch (JsonProcessingException e) {
            logger.error("字符串{}反序列化成{}对象失败，原因是：{}", jsonContent, clazz.getName(), e.getMessage());
            throw new BloomCacheException(CacheAbleConstant.TYPE_CAST_CODE, "服务器内部，字符串反序列化失败，请联系管理员！");
        }
        return t;
    }

    /**
     * 反序列化：字符串转对象集合，带泛型信息
     *
     * @param jsonContent
     * @param typeReference
     * @param <T>
     * @return
     */
    public static <T> T jsonToObject(String jsonContent, TypeReference<T> typeReference) {
        T t = null;
        try {
            t = objectMapper.readValue(jsonContent, typeReference);
        } catch (JsonProcessingException e) {
            logger.error("字符串{}反序列化成{}对象失败，原因是：{}", jsonContent, typeReference, e.getMessage());
            throw new BloomCacheException(CacheAbleConstant.TYPE_CAST_CODE, "服务器内部，字符串反序列化失败，请联系管理员！");
        }
        return t;
    }

    /**
     * 序列化：对象转字符串
     *
     * @param o
     * @return String
     */
    public static String ObjectToStr(Object o) {
        try {
            cacheStr = objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            logger.error("{}对象转字符串失败，原因是：{}", o.getClass().getName(), e.getMessage());
            throw new BloomCacheException(CacheAbleConstant.TYPE_CAST_CODE, "服务器内部错误，对象序列化成字符串失败，请联系管理员！");
        }
        return cacheStr;
    }

    /**
     * 获取所有正则规则
     *
     * @return
     */
    public static List<String> getAppAllRegex() {
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list,
                CacheAbleConstant.REGEX_RULE_FIRST,
                CacheAbleConstant.REGEX_RULE_SECOND,
                CacheAbleConstant.REGEX_RULE_THIRD);
        return list;
    }

}
